package com.tg.app.helper;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.tg.app.activity.base.DeviceListBaseActivity.OPEN_DRIVE_LOCAL_PALYBACK_SDCARD;
import static com.tg.app.activity.base.DeviceListBaseActivity.PUSH_TARGET_LIST;
import static com.tg.app.activity.base.DeviceListBaseActivity.PUSH_TARGET_PALYBACK_CLOUD;
import static com.tg.app.activity.base.DeviceListBaseActivity.PUSH_TARGET_PALYBACK_SDCARD;
import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.ImageButton;

import androidx.annotation.NonNull;

import com.appbase.custom.BuildConfig;
import com.appbase.custom.config.ApiUrl;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.UserProtocolConstants;
import com.dotview.DotTextView;
import com.inuker.bluetooth.library.search.SearchResult;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.backend.service.api.CoreApiUrl;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.core.data.structure.Response;
import com.tange.feature.data.structure.DeviceTypeBean;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tg.app.MultiVersionHelper;
import com.tg.app.R;
import com.tg.app.activity.CloudServiceActivity;
import com.tg.app.activity.WebActivity;
import com.tg.app.activity.base.CameraBaseActivity;
import com.tg.app.activity.base.WebBaseActivity;
import com.tg.app.activity.device.AddDeviceHelperActivity;
import com.tg.app.activity.device.CameraLiveActivity;
import com.tg.app.activity.device.CameraViewActivity;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.activity.device.add.Add4GChooseActivity;
import com.tg.app.activity.device.add.AddChooseActivity;
import com.tg.app.activity.device.add.AddFragmentTabActivity;
import com.tg.app.activity.device.add.AddWifiChooseActivity;
import com.tg.app.activity.device.add.ApBindHistroyDeviceListActivity;
import com.tg.app.activity.device.add.ApConnectActivityEx;
import com.tg.app.activity.device.add.ApGuideActivity;
import com.tg.app.activity.device.add.ApSearchDeviceListActivity;
import com.tg.app.activity.device.add.ApSetWifiActivityEx;
import com.tg.app.activity.device.add.DisScanDeviceActivity;
import com.tg.app.activity.device.add.GlobalAddFailedActivity;
import com.tg.app.activity.device.add.ResetDeviceActivity;
import com.tg.app.activity.device.add.ScanQrcodeActivity;
import com.tg.app.activity.device.ui.cameraview.PlayBackBaseFragment;
import com.tg.app.activity.device.ui.cameraview.SdCardPlayBackFragment;
import com.tg.app.camera.Camera;
import com.tg.app.camera.P2PReport;
import com.tg.app.statistics.TangeVideoPlayStatistics;
import com.tg.app.util.UriUtil;
import com.tg.app.view.ACCameraPlayerView;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.business.IMessageModule;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.message.msg.MessageActivity;
import com.tg.network.socket.http.TGHttp;

import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ActivityHelper {
    public static final String SWAP_PRE_TAG = "ScreenSwapActivity_";
    private static final String TAG = ActivityHelper.class.getSimpleName();
    private static final long DEFAULT_DIFF_MS = 6000;
    private static final long DEFAULT_BACKGROUND_TIME = 10 * 60 * 1000L;
    public static final String ADD_DEVICE_FROM_TYPE_CHOOSSE = "add_device_from_type_choose";
    public static final String ADD_DEVICE_FROM_SCAN_QRCODE = "add_device_from_scan_qrcode";
    public static boolean showCustomerToolbar(ImageButton btnCustomerToolbar, DotTextView dotTextView, @NonNull DeviceItem deviceItem, Activity activity){
        btnCustomerToolbar.setOnClickListener(view -> DeviceHelper.openCustomerService(deviceItem, activity));

        if (dotTextView != null){
            dotTextView.setOnClickListener(view -> DeviceHelper.openCustomerService(deviceItem, activity));
        }

        boolean show = DeviceHelper.showCustomerServer(deviceItem);
        btnCustomerToolbar.setVisibility(show? VISIBLE : GONE);
        int count = DeviceHelper.getCustomerMessageCount(deviceItem);
        dotTextView.setTipsCount(count);
        dotTextView.setVisibility(show && count > 0? VISIBLE : GONE);
        return show;
    }

    public static void showWebPopWindow(Activity activity, boolean mustClose, String url){
        Intent intent = new Intent(activity, CloudServiceActivity.class);
        intent.putExtra(WebBaseActivity.KEY_WEBURL, url);
        intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, 0);
        activity.startActivity(intent);
        if (mustClose){
            activity.finish();
        }
    }

    @SuppressLint("DefaultLocale")
    public static void gotoAddDeviceHelperPage(Context context, String url, boolean showCloseBtn, int height, int margin, String from) {
        Intent webIntent = new Intent(context, AddDeviceHelperActivity.class);
        int userId = PreferenceUtil.getInt(context, CommonConstants.PRE_USER_ID);
        String helperUrl = url;
        if (!StringUtils.isUrl(url)){
            if (CoreApiUrl.TG_STATIC.endsWith("/") && url.startsWith("/")){
                helperUrl = url.substring(1);
            }
            if (url.contains("?")){
                helperUrl = String.format("%s%s&platform=android&version=%s&user_id=%d", CoreApiUrl.TG_STATIC, helperUrl, AppUtil.getVersionName(context), userId);
            }else{
                helperUrl = String.format("%s%s?platform=android&version=%s&user_id=%d", CoreApiUrl.TG_STATIC, helperUrl, AppUtil.getVersionName(context), userId);
            }
        }

        if (!StringUtils.isEmpty(from)){
            webIntent.putExtra(AddDeviceHelperActivity.KEY_FROM_DEVICE_TIP, from);
        }

        webIntent.putExtra(WebActivity.KEY_WEBURL, helperUrl);
        webIntent.putExtra(AddDeviceHelperActivity.KEY_SHOW_CLOSE, showCloseBtn);
        webIntent.putExtra(AddDeviceHelperActivity.KEY_WEB_MARGIN, margin);
        webIntent.putExtra(AddDeviceHelperActivity.KEY_WEB_HEIGHT, height);
        webIntent.putExtra(WebActivity.KEY_WEBTITLE, "");
        context.startActivity(webIntent);
    }

    public static void gotoAddDeviceHelperPage(Context context, String url) {
        gotoAddDeviceHelperPage(context, url, true, 0, 0, null);

    }

    public static Intent getDeviceListIntent(Context context){
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClass(context, DeviceListActivity.class);
        return intent;
    }

    public static void gotoDeviceListPage(Context context) {
        context.startActivity(getDeviceListIntent(context));
    }

    public static void gotoDeviceListPage(Context context, Bundle extras) {
        context.startActivity(getDeviceListIntent(context).putExtras(extras));
    }

    public static void goToBindActivity(Activity activity, String uuid, String from) {
        ActivityHelper.goToBindActivity(activity, uuid, from, null);
    }

    public static void goToBindActivity(Activity activity, String uuid, String from, DeviceTypeBean deviceTypeBean) {
        Intent intent = new Intent(activity, ScanQrcodeActivity.class);
        intent.putExtra(ApSetWifiActivityEx.EXT_WIFI_UUID, uuid);
        intent.putExtra(ScanQrcodeActivity.EXT_FROM_HISTROY, from);
        if (deviceTypeBean != null){
            intent.putExtra(DeviceTypeBean.DEVICE_TYPE_BEAN, deviceTypeBean);
        }

        activity.startActivity(intent);
        activity.finish();
    }

    public static void gotoAddFailedActivity(Activity activity, String type, String uuid, boolean gotoAddHome){
        gotoAddFailedActivity(activity, type, uuid, gotoAddHome, false);
    }

    public static void gotoAddFailedActivity(Activity activity, String type, String uuid, boolean gotoAddHome, boolean isBluetoothDevice){
        Intent intent = new Intent(activity, GlobalAddFailedActivity.class);
        intent.putExtra(ApSetWifiActivityEx.EXT_WIFI_UUID, uuid);
        intent.putExtra(ApSetWifiActivityEx.EXT_DEVICE_BLUETOOTH, isBluetoothDevice);
        if (StringUtils.isEmpty(type)){
            intent.putExtra(ApSetWifiActivityEx.EXT_DEVICE_TYPE, type);
        }
        intent.putExtra(ApSetWifiActivityEx.EXT_GO_ADD_HOME_WHEN_RE_ADD, gotoAddHome);
        activity.startActivity(intent);
    }

    public static void gotoResetDevice(Activity activity, DeviceSettingsInfo info){
        Intent intent = new Intent();
        intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
        String url = TGGlobalConfigHelper.getInstance().getHowToResetDevice();
        if (StringUtils.isEmpty(url)){
            url = ApiUrl.APP_HELP_RESET;
        }
        UriUtil.openServePlayImpl(activity, intent, url, "", 0);
    }

    public static void gotoAddDeviceHomePage(Activity activity) {
        TGApplicationBase.getInstance().putGlobalObject(TGApplicationBase.ADD_DEVICE_FROM, ADD_DEVICE_FROM_TYPE_CHOOSSE);
        // 如果设备类型中，只配置有一个类型，那么不显示添加类型页面，自动跳过
        if ((BuildConfig.device_wifiCamera_addByFast || BuildConfig.device_wifiCamera_addByQrCode || BuildConfig.device_wifiCamera_addByWired || BuildConfig.device_4gCamera_addByQrCode) // 只有"WiFi摄像机"或者"4G摄像机"（因为这俩合并成一个"监控摄像头"了）
                && !BuildConfig.device_4gCarCamera_addByFast
                && !BuildConfig.device_4gCarCamera_addByQrCode
                && !BuildConfig.device_wifiDoorBell_addByFast
                && !BuildConfig.device_doorLock_addByFast
                && !BuildConfig.device_doorLock_addByQrCode) {
            Intent toAp = new Intent(activity, AddWifiChooseActivity.class);
            activity.startActivity(toAp);
        } else if (!BuildConfig.device_wifiCamera_addByFast
                && !BuildConfig.device_wifiCamera_addByQrCode
                && !BuildConfig.device_wifiCamera_addByWired
                && !BuildConfig.device_4gCamera_addByQrCode
                && (BuildConfig.device_4gCarCamera_addByFast || BuildConfig.device_4gCarCamera_addByQrCode) // 只有"行车记录仪"
                && !BuildConfig.device_wifiDoorBell_addByFast
                && !BuildConfig.device_doorLock_addByFast
                && !BuildConfig.device_doorLock_addByQrCode) {
            Intent carIntent = new Intent(activity, Add4GChooseActivity.class);
            activity.startActivity(carIntent);
        }  else {
            Intent toAddChoose = new Intent(activity, AddChooseActivity.class);
            activity.startActivity(toAddChoose);
        }
    }

    public static void goToDisScanDeviceActivity(Activity activity) {
        if (activity != null) {
            Intent intent = new Intent(activity, DisScanDeviceActivity.class);
            activity.startActivity(intent);
            activity.finish();
        }
    }

    private static Intent getService(DeviceItem deviceItem){
        return getService(deviceItem.id, deviceItem.uuid);
    }

    private static Intent getService(long id, String uuid){
        Intent intent = new Intent();
        DeviceSettingsInfo info = new DeviceSettingsInfo();
        info.deviceID = id;
        info.uuid = uuid;
        TGLog.d("CloudServiceActivity","info.deviceID =" + info.deviceID);
        intent.putExtra(EXT_DEVICE_INFO, info);
        return intent;
    }

    private static Intent getService(Context context, DeviceItem deviceItem, int type){
        Intent intent = getService(deviceItem);
        intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, type);
        intent.setClass(context, CloudServiceActivity.class);
        return intent;
    }

    public static void openCarService(Context context, DeviceItem deviceItem){
        Intent intent = getService(deviceItem);
        String url = ApiUrl.CAR_DETAIL_PAGE;
        intent.putExtra(CloudServiceActivity.KEY_WEBURL, url);
        intent.putExtra(WebBaseActivity.KEY_WEBTITLE, context.getString(R.string.settings_device_car));
        intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, 0);
        intent.setClass(context, CloudServiceActivity.class);
        context.startActivity(intent);
    }

    public static void openCarService(Context context, long id, String uuid){
        Intent intent = getService(id, uuid);
        String url = ApiUrl.CAR_DETAIL_PAGE;
        intent.putExtra(CloudServiceActivity.KEY_WEBURL, url);
        intent.putExtra(WebBaseActivity.KEY_WEBTITLE, context.getString(R.string.settings_device_car));
        intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, 0);
        intent.setClass(context, CloudServiceActivity.class);
        context.startActivity(intent);
    }


    public static void openWebService(Context context, DeviceItem deviceItem, int type) {
//        TGLog.d("CloudServiceActivity","openWebService type =" + type);
//        TGLog.d("CloudServiceActivity","deviceItem.id =" + deviceItem.id);
//        Intent intent = getService(context, deviceItem, type);
//        context.startActivity(intent);

        TGToast.showToast("该功能暂未开放");
    }

    public static void openVIPService(Context context, DeviceItem deviceItem) {
        int type = CloudServiceActivity.EXT_LOCKBELL_SERVICE_TYPE_STORAGEORCAR;
        if (DeviceHelper.isDoorBell(deviceItem)){
            type = CloudServiceActivity.EXT_DOORBELL_SERVICE_TYPE_STORAGEORCAR;
        }else if (DeviceHelper.isBirdFeeder(deviceItem)){
            type = CloudServiceActivity.EXT_BIRD_FEEDER_SERVICE_TYPE_STORAGEORCAR;
        }
        Intent intent = getService(context, deviceItem, type);
        if (context instanceof Activity){
            ((Activity)context).startActivityForResult(intent, Activity.RESULT_FIRST_USER);
            return;
        }
        context.startActivity(intent);
    }

    public static void startCameraActivityFromMessage(Activity activity, @NonNull MessageDataBean.ItemsBean eventMessage, DeviceItem device, boolean isCloud) {
        long diffMS = System.currentTimeMillis() - eventMessage.getStart_ts();
        String startMS = eventMessage.getStart_time();
        startCameraActivity(activity, startMS, diffMS, device, isCloud, P2PReport.MESSAGE_DETAIL_PAGE);
    }

    public static void startCameraActivity(Activity activity, String startMS, long diffMS, DeviceItem device, boolean isCloud, String from) {
        TangeVideoPlayStatistics.resetStartTimeTotal();
        TGLog.d(TAG, "isCloud = " + isCloud + ", from = " + from + ", startMS = " + startMS + ", diffMS = " + diffMS);
        TGLog.trace();
        Intent intent = new Intent();
        intent.setClass(activity, CameraLiveActivity.class);
        intent.putExtra(CameraBaseActivity.FROM, from);
        if (diffMS > DEFAULT_DIFF_MS) {
            intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, isCloud ? PUSH_TARGET_PALYBACK_CLOUD : PUSH_TARGET_PALYBACK_SDCARD);
            if (DeviceHelper.isCar(device) && !isCloud) {
                intent.setClass(activity, CameraLiveActivity.class);
                intent.putExtra(CameraBaseActivity.FROM, P2PReport.DEVICE_SCARD_PAGE);
                intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, OPEN_DRIVE_LOCAL_PALYBACK_SDCARD);
                String wifi = DeviceHelper.getDeviceWifi(device.uuid);
                WiFiScanManager.scanner().addCameraWifi(wifi, activity);
            }
        } else {
            intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, PUSH_TARGET_LIST);
        }

        if (!TextUtils.isEmpty(device.p2p_id) || DeviceHelper.isExistLockBellRelay(device)) {
            intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, device);
            intent.putExtra(CommonConstants.EXT_JUMP_EVENT_TIME, startMS);
            activity.startActivityForResult(intent, 0);
        }
    }


    /**
     * 打开一个设备，看视频
     */
    public static void openCarDevice(Context context, DeviceItem device) {
        TangeVideoPlayStatistics.resetStartTimeTotal();
        if (!WiFiUtilWrapper.checkWifiAndLocation(context)) {
            return;
        }
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(device.uuid)) {
            String wifi = DeviceHelper.getDeviceWifi(device.uuid);
            TGLog.d("Cs2Camera", "wifi = " + wifi);
            WiFiScanManager.scanner().addCameraWifi(wifi, context);
            intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, OPEN_DRIVE_LOCAL_PALYBACK_SDCARD);
        }

        intent.setClass(context, CameraViewActivity.class);
        //todo p2p_id 为空 默认为tutk
        if (!TextUtils.isEmpty(device.p2p_id) || DeviceHelper.isExistLockBellRelay(device)) { // 尚云 p2p
            TGLog.d(TAG, "[openCarDevice] connect == ");
            intent.putExtra(CameraBaseActivity.FROM, P2PReport.DEVICE_SCARD_PAGE);
            intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, device);
            context.startActivity(intent);
        }
    }

    private static void setCameraEnableSearch(Camera camera, boolean b) {
        if (b) {
            camera.setClickTime(0);
            camera.disconnect();
            camera.enableLanSearch();
        }
    }

    public static boolean isLocalConnect(Activity activity){
        if (activity instanceof CameraBaseActivity){
            return ((CameraBaseActivity) activity).isLocalConnect();
        }
        return false;
    }

    public static PlayBackBaseFragment createPlayBackFragment(){
        return new SdCardPlayBackFragment();
    }

    public static PlayBackBaseFragment newInstance(int playType, DeviceItem deviceItem, boolean isAnimationsStart) {
        TGLog.d(TAG, "isAnimationsStart = " + isAnimationsStart);
        PlayBackBaseFragment fragment = createPlayBackFragment();
        Bundle args = new Bundle();
        args.putInt(PlayBackBaseFragment.EXT_PLAYBACK_TYPE, playType);
        args.putParcelable(CommonConstants.EXT_DEVICE_ITEM, deviceItem);
        args.putBoolean(PlayBackBaseFragment.EXT_PLAYBACK_START, isAnimationsStart);
        fragment.setArguments(args);

        return fragment;
    }

    public static void connectImpl(CameraViewActivity cameraViewActivity, @NonNull Camera camera, boolean startMedia){
        if (cameraViewActivity != null) {
            if (camera.connectionState == Camera.CONNECTION_STATE_CONNECTED) {
                if (!camera.isRunningLiveVideo()) {
                    cameraViewActivity.reportFirstFramePrepare();
                    cameraViewActivity.reportFirstFrameP2P();
                    cameraViewActivity.startLive();
                    if (startMedia){
                        cameraViewActivity.getPlayerView().mediaSyncStart();
                    }
                }
            } else {
                cameraViewActivity.setLiveClicked(false);
                cameraViewActivity.connect();
            }
        }
    }

    public static void connect(CameraViewActivity cameraViewActivity, @NonNull Camera camera){
        connectImpl(cameraViewActivity, camera, false);
    }

    public static boolean connectEx(CameraBaseActivity cameraViewActivity, @NonNull Camera camera){
        if (cameraViewActivity != null && !camera.isConnected()) {
            cameraViewActivity.setLiveClicked(false);
            cameraViewActivity.connect();
            return false;
        }
        return true;
    }

    public static void showLoading(Activity activity, ACCameraPlayerView cameraPlayerView){
        showLoading(activity, cameraPlayerView, null);
    }

    public static void showLoading(Activity activity, ACCameraPlayerView cameraPlayerView, String text){
        if (cameraPlayerView !=  null){
            cameraPlayerView.setLoadingVisibility(View.VISIBLE, text);
        }
    }

    public static Context getActivityContext(Context context){
        if (context instanceof Activity){
            if (((Activity)context).isFinishing()){
                context = TGApplicationBase.getInstance().getActivity(DeviceListActivity.class.getSimpleName());
            }
        }else{
            context = TGApplicationBase.getInstance().getActivity(DeviceListActivity.class.getSimpleName());
        }
        return context;
    }

    public static void startLoginActivity(Context context, String from){
        MultiVersionHelper.startLoginActivity(context, from);
    }

    public static void startRegisterActivity(Context context){
        MultiVersionHelper.startRegisterActivity(context);
    }

    public static void startForgotPasswordActivity(Context context){
        MultiVersionHelper.startForgotPasswordActivity(context);
    }

    public static void setBackButton(Activity activity, boolean show){
        if (activity instanceof CloudServiceActivity){
            if (!AppUtil.isActivityFinishingOrDestroyed(activity)){
                ((CloudServiceActivity)activity).setBackButton(show);
            }
        }
    }

    public static void setCloseButton(Activity activity, boolean show){
        if (activity instanceof AddDeviceHelperActivity){
            if (!AppUtil.isActivityFinishingOrDestroyed(activity)){
                ((AddDeviceHelperActivity)activity).setCloseButton(show);
            }
        }
    }

    public static void goToDeviceListActivity(Activity activity) {
        if (System.currentTimeMillis() - TGApplicationBase.getInstance().getBackgroundTime() > DEFAULT_BACKGROUND_TIME) {
            TGLog.d("times = " + (System.currentTimeMillis() - TGApplicationBase.getInstance().getBackgroundTime()) / 1000);
            ActivityHelper.gotoDeviceListPage(activity);
        }
    }

    public static void goToMessageActivity(Context context, DeviceItem deviceItem){
        Intent intent = new Intent(context, MessageActivity.class);
        intent.putExtra(IMessageModule.EXT_MESSAGE_DEVICE, deviceItem);
        intent.putExtra(IMessageModule.EXT_MESSAGE_DEVICE_AI_ENABLE, false);
        ArrayList<DeviceItem> deviceItems = new ArrayList<>();
        deviceItems.add(deviceItem);
        intent.putExtra(IMessageModule.EXT_EVENT_DEVICES, deviceItems);
        if (!(context instanceof Activity)){
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }



    public static void jump2SettingActivityForResult(Activity activity, DeviceItem deviceItem, int origin){
        Intent intent = new Intent();
        intent.setClass(activity, DeviceSettingsActivity.class);
        intent.putExtra(CommonConstants.EXT_PUSH_ORIGIN, origin);
        intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, deviceItem);
        activity.startActivityForResult(intent, 0);
    }

    public static void jump2ResetDeviceActivity(Context context, String uuid, Intent intent){
        if (intent == null){
            intent = new Intent(context, ResetDeviceActivity.class);
        }
        intent.putExtra(ApSetWifiActivityEx.EXT_WIFI_UUID, uuid);
        context.startActivity(intent);
    }


    public static void goToBindHistroyDeviceListActivity(Context context){
        Intent intent = new Intent(context, ApBindHistroyDeviceListActivity.class);
        context.startActivity(intent);
    }

    public static void goToSearchWifi(Context context){
        Intent intent = new Intent(context, ApSearchDeviceListActivity.class);
        context.startActivity(intent);
    }

    public static void setButtonEnable(@NonNull Button button, boolean enabled){
        button.setEnabled(enabled);
        button.setAlpha(enabled? 1.f : 0.4f);
    }


    public static void goToConnectActivity(final Activity activity, final String name, final String pwd, final String uuid, final String bindToken, final long startTime, String from) {
        goToConnectActivity(activity, name, pwd, uuid, bindToken, startTime, from, true, null);
    }

    public static void goToConnectActivity(final Activity activity, final String name, final String pwd, final String uuid, final String bindToken, final long startTime, String from, boolean playSound, SearchResult searchResult) {
        TGThreadPool.executeOnUiThread(() -> {
            Intent intent = new Intent(activity, ApConnectActivityEx.class);
            intent.putExtra(ApSetWifiActivityEx.EXT_WIFI_UUID, uuid);
            intent.putExtra(ApSetWifiActivityEx.EXT_WIFI_NETWORD, name);
            intent.putExtra(ApSetWifiActivityEx.EXT_WIFI_PWD, pwd);
            intent.putExtra(ApConnectActivityEx.EXT_BIND_TOKEN, bindToken);
            intent.putExtra(ApConnectActivityEx.EXT_FROM_CONNECT, from);
            intent.putExtra(ApConnectActivityEx.EXT_PLAY_SOUND, playSound);
            if (searchResult != null){
                intent.putExtra(ApSetWifiActivityEx.EXT_DEVICE_BLUETOOTH, searchResult);
            }

            long time = startTime;
            if (time == 0) {
                time = System.currentTimeMillis();
            }
            intent.putExtra(ApConnectActivityEx.EXT_BIND_START_TIME, time);
            activity.startActivity(intent);
            activity.finish();
        });
    }


    public static void getAgreementForWebView(final Context context, int flag) {
        final String title;
        final String data;
        if (flag == UserProtocolConstants.PRIVACY) {
            title = context.getString(R.string.privacy_policy);
            data ="https://tange-ai.feishu.cn/docx/VNXPdVk72orjl3xCIvLcRPoAnDb";
        } else {
            title = context.getString(R.string.user_agreement);
            data ="https://tange-ai.feishu.cn/docx/Abu5d54sTomqyQxblkKcwFEunMb";
        }
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(WebActivity.KEY_WEBURL, data);
        intent.putExtra(WebActivity.KEY_WEBTITLE, title);
        context.startActivity(intent);
    }

    public static void goToWifiDeviceByHotspot(Context context){
        Intent intent = new Intent();
        if (CameraHub.getInstance().isEnableLocalApConnect()) {
            intent.setClass(context, AddFragmentTabActivity.class);
            intent.putExtra(AddFragmentTabActivity.EXT_DEVICE_ADD_TYPE, AddFragmentTabActivity.DEVICE_ADD_TYPE_AP);
        } else {
            intent.setClass(context, ApGuideActivity.class);
        }
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void goToCodeWifiDeviceActivity(Context context, int deviceAddTypeQrcode) {
        Intent intent = new Intent(context, AddFragmentTabActivity.class);
        intent.putExtra(AddFragmentTabActivity.EXT_DEVICE_ADD_TYPE, deviceAddTypeQrcode);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void setLoginStyleButtonEnable(@NonNull Button button, boolean enabled){
        button.setEnabled(enabled);
        ViewParent viewParent = button.getParent();
        if (viewParent instanceof View){
            ((View)viewParent).setAlpha(enabled? 1.f : 0.2f);
        }
    }

    public static boolean getSwapScreen(Context context, String uuid, int userId){
        return PreferenceUtil.getBoolean(context, SWAP_PRE_TAG + uuid + "_" + userId ,false);
    }

    public static void setSwapScreen(Context context, String uuid, int userId, boolean swap){
        PreferenceUtil.setBoolean(context, SWAP_PRE_TAG + uuid + "_" + userId ,swap);
    }
}
